/*
 * @Author: your name
 * @Date: 2020-08-10 11:14:37
 * @LastEditTime: 2020-09-27 11:24:47
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \devopsh:\project\QMangolia-web\src\utils\request.js
 */
import Vue from 'vue'
import axios from 'axios'
import { MessageBox } from 'element-ui'
import store from '@/store'
import { getToken, removeToken } from '@/utils/auth'
import { message } from '@/utils/resetMessage';

/**
 * axios 网络请求模块 创建
 * @type {AxiosInstance}
 */
const service = axios.create({
  baseURL: process.env.VUE_APP_API_HOST, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 60000 // request timeout
})

/**
 * request 请求拦截器1234561111
 */
service.interceptors.request.use(
  config => {
    // 数据请求 头信息
    if (store.getters.token) {
      config.headers['Authorization'] = 'Bearer ' + getToken()
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

/**
 * response 回调拦截器
 */
service.interceptors.response.use(
  response => {
    const res = response.data
    /**
     * 正确回调code 200
     */
    if (res.code !== 200) {
      /**
       * Token 验证失败
       *    50008: 非法
       *    50012: 其他环境
       *    50014: 过期
       */
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        removeToken()
        MessageBox.confirm(res.message || '请重新登录!', '身份令牌错误：', {
          confirmButtonText: '刷新页面',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('userState/state', { 'keyName': 'resetState', 'value': '' }).then(() => {
            window.location.reload()
          })
        })
        return false
      }
      /**
       * 未知错误
       */
      message.error(res.message || '数据异常! 请重试')
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      // console.log('this.$fullName', this.$fullName)
      // this.$fullName.showName({first:'张',lastName:'五'})
      return res
    }
  },
  error => {
    message.error(error.message)
    return Promise.reject(error)
  }
)

export default service
